package com.zmx.doctor.view.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;

import com.netease.nim.avchatkit.AVChatKit;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.zmx.doctor.BaseActivity;
import com.zmx.doctor.MainActivity;
import com.zmx.doctor.NimSDKOptionConfig;
import com.zmx.doctor.R;
import com.zmx.doctor.okhttp.OkHttp3ClientManager;
import com.zmx.doctor.utils.TimeCount;
import com.zmx.doctor.view.util.MySharedPreferences;
import com.zmx.doctor.wangyiyun.DemoCache;
import com.zmx.doctor.wangyiyun.saveData.DataSaveToLocal;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity {


    @BindView(R.id.registered)
    Button registered_button;
    @BindView(R.id.tool_bar)
    Toolbar toolBar;
    @BindView(R.id.et_account)
    EditText etAccount;
    @BindView(R.id.pwd_edt)
    EditText pwdEdt;
    @BindView(R.id.code)
    TextView code_button;
    @BindView(R.id.no_code)
    TextView noCode;
    @BindView(R.id.number_pwd)
    TextView numberPwd;
    @BindView(R.id.login)
    Button login_button;
    @BindView(R.id.pwd_layout_a)
    RelativeLayout pwdLayoutA;
    @BindView(R.id.pwd_layout_b)
    RelativeLayout pwdLayoutB;
    @BindView(R.id.pwd_edit)
    EditText pwdEdit;

    private String phone_number;
    private String filePath;

    private DataSaveToLocal dataSaveToLocal = new DataSaveToLocal();

    private int CODE_PWD = 0;//0为验证码登录，1为密码登录

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initViews() {

        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);

        filePath = NimSDKOptionConfig.getAppCacheDir(getApplicationContext())+"logininfo.txt";

    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:
                    login();
                    break;
                case 2:
                    try {


                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        String data = jsonObject.getString("data");

                        if (jsonObject.getInt("code") == 1) {

                            Toast("登录成功");
                            //保存登录成功的信息
                            JSONObject info = new JSONObject(new JSONObject(data).getString("info"));
                            MySharedPreferences.getInstance(mActivity).saveKeyObjValue(MySharedPreferences.token, info.getString("token"));
                            MySharedPreferences.getInstance(mActivity).saveKeyObjValue(MySharedPreferences.uid, info.getString("uid"));
                            MySharedPreferences.getInstance(mActivity).saveKeyObjValue(MySharedPreferences.role, info.getString("role"));
                            MySharedPreferences.getInstance(mActivity).saveKeyObjValue(MySharedPreferences.name, info.getString("name"));
                            MySharedPreferences.getInstance(mActivity).saveKeyObjValue(MySharedPreferences.yx_token,info.getString("yx_token"));
                            MySharedPreferences.getInstance(mActivity).saveKeyObjValue(MySharedPreferences.avatar, info.getString("avatar"));
                            MySharedPreferences.getInstance(mActivity).saveKeyObjValue(MySharedPreferences.mobile, info.getString("mobile"));
                            MySharedPreferences.getInstance(mActivity).saveKeyObjValue(MySharedPreferences.password, info.getString("password"));
                            MySharedPreferences.getInstance(mActivity).saveKeyObjValue(MySharedPreferences.unread_message,false);
                            MySharedPreferences.getInstance(mActivity).saveKeyObjValue(MySharedPreferences.isLogin, true);


                            //实例化logininfo，执行登陆
                            LoginInfo loginInfo = new LoginInfo(info.getString("uid"),info.getString("yx_token"));
                            doLogin(loginInfo);

                        }else{
                            Toast(jsonObject.getString("msg"));
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();

                    }

                    break;

                case 3:


                    try {

                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        Toast(jsonObject.getString("msg"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 404:

                    Toast("系统错误");
                    break;
            }

        }
    };

    @OnClick({R.id.registered,R.id.code, R.id.no_code, R.id.number_pwd, R.id.login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //注册
            case R.id.registered:
                startActivity(RegisteredActivity.class);
                break;
            case R.id.code:

                //判断用户输入是否为空
                if (getAccount().isEmpty()) {
                    Toast("你输入的账号为空！");
                    return;
                }
                if (!isChinaPhoneLegal(getAccount())) {
                    Toast("输入正确的手机号码！");
                    return;
                }

                getCode();
                //拿到正确的手机号
                phone_number = getAccount();
                TimeCount timeCount = new TimeCount(code_button, 60000, 1000);
                timeCount.start();

                break;
            case R.id.no_code:



                break;
            case R.id.number_pwd:


                if (CODE_PWD == 0) {

                    pwdLayoutA.setVisibility(View.GONE);
                    pwdLayoutB.setVisibility(View.VISIBLE);
                    numberPwd.setText("短信验证码登录");
                    CODE_PWD = 1;

                } else {

                    pwdLayoutA.setVisibility(View.VISIBLE);
                    pwdLayoutB.setVisibility(View.GONE);
                    numberPwd.setText("账号密码登录");
                    CODE_PWD = 0;
                }

                break;
            case R.id.login:

                //判断是密码登录还是验证码登录 0为验证码登录，1为密码登录
                if (CODE_PWD == 0) {

//                    判断用户输入是否为空
                    if (getAccount().isEmpty()) {
                        Toast("你输入的账号为空！");
                        return;
                    }
                    if (!isChinaPhoneLegal(getAccount())) {
                        Toast("输入正确的手机号码！");
                        return;
                    } if (pwdEdt.getText().toString().isEmpty()) {
                        Toast("请输入验证码！");
                        return;
                    }
                    //手机验证码登录
                    handler.sendEmptyMessage(1);


                } else {


                    if (getAccount().isEmpty()) {
                        Toast("你输入的账号为空！");
                        return;
                    }
                    if (!isChinaPhoneLegal(getAccount())) {
                        Toast("输入正确的手机号码！");
                        return;
                    } if (pwdEdit.getText().toString().isEmpty()) {
                        Toast("请输入密码！");
                        return;
                    }
                    userLogin();
                }

                break;
        }
    }

    /**
     * 获取手机号
     */
    public String getAccount() {
        return etAccount.getText().toString().trim();//去掉空格
    }

    /**
     * 获取密码
     */
    public String getPassword() {
        return pwdEdt.getText().toString().trim();//去掉空格
    }


    /**
     * 大陆手机号码11位数，匹配格式：前三位固定格式+后8位任意数
     * 此方法中前三位格式有：
     * 13+任意数
     * 145,147,149
     * 15+除4的任意数(不要写^4，这样的话字母也会被认为是正确的)
     * 166
     * 17+3,5,6,7,8
     * 18+任意数
     * 198,199
     */
    public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
        // ^ 匹配输入字符串开始的位置
        // \d 匹配一个或多个数字，其中 \ 要转义，所以是 \\d
        // $ 匹配输入字符串结尾的位置
        String regExp = "^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[3,5,6,7,8])" +
                "|(18[0-9])|(19[8,9]))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }


    /**
     * 提交注册
     */
    public void login() {


        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("data[mobile]", getAccount());
        params.put("data[code]",pwdEdt.getText().toString());
        params.put("data[role]", "2");
        params.put("cmd", "smslogin");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/api/", params, handler, 2, 404);

    }

    /**
     * 提交
     */
    public void getCode(){

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("data[mobile]",getAccount());
        params.put("data[type]","user");
        params.put("data[role]","2");
        params.put("cmd","sendsms");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/api/", params, handler, 3, 404);

    }

    public void userLogin(){

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("data[mobile]",getAccount());
        params.put("data[password]",pwdEdit.getText().toString());
        params.put("data[role]","2");
        params.put("cmd","userLogin");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/api/", params, handler, 2, 404);

    }

    /**
     * 执行登陆
     * @param loginInfo
     */
    private void doLogin(LoginInfo loginInfo){
        RequestCallback<LoginInfo> callback = new RequestCallback<LoginInfo>() {
            @Override
            public void onSuccess(LoginInfo loginInfo) {

                Toast.makeText(LoginActivity.this, "登陆成功！", Toast.LENGTH_SHORT).show();
                DemoCache.setContext(getApplicationContext());
                AVChatKit.setAccount(loginInfo.getAccount());
                //判断是否需要本地存储密码(CheckBox打钩)
//                if (needRecordPassword){
                    dataSaveToLocal.saveDataToLocal(loginInfo.getAccount()+","+loginInfo.getToken(),filePath);
//                }else {//删除文件
//                    dataSaveToLocal.deleteFile(filePath);
//                }
                //跳转到拨打界面
                Intent intent = new Intent();
                intent.setClass(mActivity, MainActivity.class);
                startActivity(intent);
                finish();

            }

            @Override
            public void onFailed(int i) {

                Toast.makeText(LoginActivity.this, "登陆失败，错误码："+i, Toast.LENGTH_SHORT).show();

                //充钱就删的
                Intent intent = new Intent();
                intent.setClass(mActivity, MainActivity.class);
                startActivity(intent);
                finish();


            }

            @Override
            public void onException(Throwable throwable) {
                Toast.makeText(LoginActivity.this, "登陆异常，" + throwable.toString(), Toast.LENGTH_SHORT).show();
            }
        };
        NIMClient.getService(AuthService.class).login(loginInfo).setCallback(callback);
    }


}
